package com.shuqi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.CountDownTimmerViewRegister;
import com.shuqi.activity.viewport.PhoneEditTextView;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.RegexUtil;
import com.shuqi.controller.AcountBindVerifyCodeController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.parse.parser.AccountBindGetValidationParser;
import com.shuqi.model.parse.parser.AccountBindGetValidationParser.AccountBindValidationInfo;
import com.shuqi.model.parse.parser.AccountBindVerifyParser;
import com.shuqi.model.parse.parser.AccountBindVerifyParser.AccountBindByPhoneInfo;

/**
 * 手机注册
 * 
 * @author liyizhe
 * 
 */
public class MobileRegisterActivity extends ActivityBase implements OnClickListener,
        OnFocusChangeListener, IEventListener {

    private boolean isSeparatedText = true;

    private TextView mTextShuQi = null;// 书旗用户协议
    private TextView mBtnNext = null;// 下一步
    CountDownTimmerViewRegister mViewTimer = null;// 计时器
    private CheckBox mCheckBox = null;

    private EditText mEditIdentify = null; // 验证码输入框
    private PhoneEditTextView mPhoneNumber = null;// 电话号

    private TextView mTextMobilePoinTextView = null; // 邮箱提示
    private TextView mTextPwdPoinTextView = null; // 密码提示

    private AcountBindVerifyCodeController mVerifyController;// 验证码获取和验证接口

    private final int INIT = EventTypeConstants.BASE;
    private final int SAVEDETAILS = INIT + 1;
    private final int INITSUCCESS = SAVEDETAILS + 1;
    private final int NETERROR = INITSUCCESS + 1;

    private ToastDialog mLoadingDialog;// 底部loading
    private CommonTitle mTitle;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    break;
                case NETERROR:
                    //setCountDownTimmerView(COUNT_DOWN_MODE_RESET);
                    mViewTimer.reset();
                    hideLoadingDialog();
                    showMsg("网络连接超时");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mVerifyController =
                (AcountBindVerifyCodeController) MainController.getMainManagerInstance()
                        .createController(MainController.ACCOUNT_ID_BIND, this);
        mVerifyController.addEventListener(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_phone_register);

        handler.sendEmptyMessage(INIT);
    }


    @Override
    public void onEvent(int event, final Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                // 读取数据 写处理逻辑
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        onNetWorkCallback(data);
                    }
                };
                ShuqiApplication.getApplicationHandler().post(r);
                break;
            case EventTypeConstants.EVENT_EXC_IO_2:
                handler.sendEmptyMessage(NETERROR);
                break;
            default:
                handler.sendEmptyMessage(NETERROR);
                break;
        }
    }


    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        mTextShuQi = (TextView) findViewById(R.id.proxy_text2);
        mCheckBox = (CheckBox) findViewById(R.id.checkBox_mobile);
        mBtnNext = (TextView) findViewById(R.id.bind_next);
        mEditIdentify = (EditText) findViewById(R.id.edit_validation);
        mPhoneNumber = (PhoneEditTextView) findViewById(R.id.edit_mobile);
        mViewTimer = (CountDownTimmerViewRegister) findViewById(R.id.text_validation);
        mTextMobilePoinTextView = (TextView) findViewById(R.id.mobile_point);
        mTextPwdPoinTextView = (TextView) findViewById(R.id.identify_point);

        mBtnNext.setOnClickListener(this);
        mViewTimer.setOnClickListener(this);
        mTextShuQi.setOnClickListener(this);
        mPhoneNumber.setOnFocusChangeListener(this);
        mPhoneNumber.addTextChangedListener(textWatcher);
        
        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    @Override
    public void activityInitData() {
        // TODO Auto-generated method stub

    }

    /**
     * 监听判断电话字符
     */
    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable editable) {
            if (isSeparatedText) {
                String mobileStr = mPhoneNumber.getString();
                if (!TextUtils.isEmpty(mobileStr) && RegexUtil.isMobileNO(mobileStr)) {
                    separatedText(mobileStr, true);
                } else {
                    separatedText(mobileStr, false);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence charsequence, int i, int j, int k) {}

        @Override
        public void onTextChanged(CharSequence charsequence, int i, int j, int k) {}
    };

    /**
     * 号码分格
     */
    private void separatedText(String inputText, boolean isRight) {
        isSeparatedText = false;
        if (isRight) {
            StringBuilder resultStr = new StringBuilder();
            resultStr.append(inputText.substring(0, 3)).append("-")
                    .append(inputText.substring(3, 7)).append("-").append(inputText.substring(7));
            mPhoneNumber.setText(resultStr.toString());
            mPhoneNumber.setSelection(resultStr.length());
        } else {
            mPhoneNumber.setText(inputText);
            mPhoneNumber.setSelection(inputText.length());
        }
        isSeparatedText = true;
    }

    /**
     * 网络返回数据处理
     * 
     * @param data
     */
    private void onNetWorkCallback(Object data) {

        if (data instanceof AccountBindGetValidationParser.AccountBindValidationInfo) {
            hideLoadingDialog();
            // 获取验证码返回
            AccountBindValidationInfo info = (AccountBindValidationInfo) data;
            if (info != null) {
                String msg = info.msg;
                if (!TextUtils.isEmpty(msg)) {
                    showMsg(msg);
                }
                if ("200".equals(info.state)) {
                    // 下发成功
                    //setCountDownTimmerView(COUNT_DOWN_MODE_START);
                    mViewTimer.start();
                } else {
                    // 下发失败
                    //setCountDownTimmerView(COUNT_DOWN_MODE_RESET);
                    mViewTimer.reset();
                }
            }

        } else if (data instanceof AccountBindVerifyParser.AccountBindByPhoneInfo) {
            // 验证手机号和验证码接口返回
            AccountBindByPhoneInfo info = (AccountBindByPhoneInfo) data;
            hideLoadingDialog();
            if (info != null) {
                // int code = Integer.parseInt(info.state);
                String code = info.state;
                if (code.equals("200")) {
                    // goto 设置密码页面
                    Intent intent =
                            new Intent(MobileRegisterActivity.this, MobileRegisterPwdActivity.class);
                    intent.putExtra("identifycode", mEditIdentify.getText().toString());
                    intent.putExtra("phoneNumber", mPhoneNumber.getString());
                    ActivityManager.getInstance().startNextActivity(intent, this);
                }
                String msg = info.msg;
                if (!TextUtils.isEmpty(msg)) {
                    showMsg(msg);
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.text_validation:
                getValidationCode();
                break;
            case R.id.bind_next:
                nextStepRegister();
                break;
            case R.id.proxy_text2: {
                WebKitActivity.openRegisterProtocol(this);
            }
                break;
            default:
                break;
        }
    }

    private static final int COUNT_DOWN_MODE_LADING = 1;

    private static final int COUNT_DOWN_MODE_START = 2;

    private static final int COUNT_DOWN_MODE_RESET = 3;

    // 设置验证码textview的状态
    private void setCountDownTimmerView(int mode) {
        switch (mode) {
            case COUNT_DOWN_MODE_LADING:
                mViewTimer.setText("获取中");
                mViewTimer.setClickable(false);
                break;

            case COUNT_DOWN_MODE_START:
                mViewTimer.start();
                mViewTimer.setBackgroundResource(R.drawable.identify_code_n);
                mViewTimer.setTextColor(android.graphics.Color.parseColor("#b9b9b9"));
                break;

            case COUNT_DOWN_MODE_RESET:
                mViewTimer.setText("获取验证码");
                mViewTimer.setClickable(true);
                break;

            default:
                break;
        }
    }

    /**
     * 获取验证码
     */
    private void getValidationCode() {
        // 判断手机号格式
        String mobileStr = mPhoneNumber.getString();
        if (TextUtils.isEmpty(mobileStr)) {
            EmptyPhoneNumberPoint();
            return;
        } else {
            mTextMobilePoinTextView.setVisibility(View.INVISIBLE);
        }

        boolean isPhoneNumber = RegexUtil.isMobileNO(mobileStr);
        if (!isPhoneNumber) {
            ErrorPhoneNumberPoint();
            return;
        } else {
            mTextMobilePoinTextView.setVisibility(View.INVISIBLE);
        }

        // 发送并改变状态
        //setCountDownTimmerView(COUNT_DOWN_MODE_LADING);
        mViewTimer.loading();
        showLoadingDialog(true, false, "正在获取验证码");
        mVerifyController.handle(
                AcountBindVerifyCodeController.ACCOUNT_BIND_VALIDATION/* 发送or验证 */, mobileStr,
                AcountBindVerifyCodeController.REGISTER_TYPE/* 验证码注册用 */);
    }

    /**
     * 点击下一步
     */
    private void nextStepRegister() {
        if (!mCheckBox.isChecked()) {
            return;
        }

        String mobileStr = mPhoneNumber.getString();
        String validationCode = mEditIdentify.getText().toString();
        boolean isOK = isEnableFormat();// 判断格式
        if (!isOK) {
            return;
        }

        mVerifyController.handle(AcountBindVerifyCodeController.ACCOUNT_BIND_NEXT, mobileStr,
                validationCode, AcountBindVerifyCodeController.REGISTER_TYPE);
        showLoadingDialog(true, false, "正在验证");
    }

    /**
     * 判断输入的电话\验证码格式
     */
    private boolean isEnableFormat() {
        String mobileStr = mPhoneNumber.getString();
        String validationCode = mEditIdentify.getText().toString();

        if (TextUtils.isEmpty(mobileStr)) {
            EmptyPhoneNumberPoint();
            return false;
        } else if (!RegexUtil.isMobileNO(mobileStr)) {
            ErrorPhoneNumberPoint();
            return false;
        } else {
            mTextMobilePoinTextView.setVisibility(View.INVISIBLE);
        }

        if (TextUtils.isEmpty(validationCode)) {
            EmptyIdentifyPoint();
            return false;
        } else {
            mTextPwdPoinTextView.setVisibility(View.INVISIBLE);
        }

        return true;
    }


    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (view.getId() == R.id.edit_mobile) {
            if (hasFocus) {
                ((RelativeLayout) findViewById(R.id.layout_mobile))
                        .setBackgroundResource(R.drawable.input_box_f);
                mEditIdentify.setBackgroundResource(R.drawable.input_box_n);

                // 电话获得焦点，验证码提示消失，电话提示消失
                mTextPwdPoinTextView.setVisibility(View.INVISIBLE);
                mTextMobilePoinTextView.setVisibility(View.INVISIBLE);
            } else {
                ((RelativeLayout) findViewById(R.id.layout_mobile))
                        .setBackgroundResource(R.drawable.input_box_n);
                mEditIdentify.setBackgroundResource(R.drawable.input_box_f);

                // 电话失去焦点,验证码获得焦点
                if (TextUtils.isEmpty(mPhoneNumber.getString())) {
                    EmptyPhoneNumberPoint();
                } else if (!RegexUtil.isMobileNO(mPhoneNumber.getString())) {
                    ErrorPhoneNumberPoint();
                } else {
                    mTextMobilePoinTextView.setVisibility(View.INVISIBLE);// 手机号又正确
                    mTextPwdPoinTextView.setVisibility(View.INVISIBLE);// 验证码获得焦点，验证码错误提示消失
                }
            }
        }
    }

    /**
     * 显示底部加载
     */
    private void showLoadingDialog(boolean isLoading, boolean isSuccess, String showText) {
        if (isFinishing()) {
            return;
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = new ToastDialog(this);
            mLoadingDialog.setDissmisOnClickOutSide(false);
        }
        if (isLoading) {
            mLoadingDialog.loading(showText);
            return;
        }
        mLoadingDialog.setDissmisOnClickOutSide(true);
        mLoadingDialog.show(isSuccess, showText);

    }

    private void hideLoadingDialog() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                if (mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }

    /**
     * 空手机号
     */
    private void EmptyPhoneNumberPoint() {
        mTextMobilePoinTextView.setVisibility(View.VISIBLE);
        mTextMobilePoinTextView.setText("请输入手机号");
        mTextMobilePoinTextView.setTextColor(android.graphics.Color.parseColor("#494949"));
    }

    /**
     * 错误手机号
     */
    private void ErrorPhoneNumberPoint() {
        mTextMobilePoinTextView.setVisibility(View.VISIBLE);
        mTextMobilePoinTextView.setText("手机号格式错误，请重新输入");
        mTextMobilePoinTextView.setTextColor(android.graphics.Color.parseColor("#ff361b"));
    }

    /**
     * 空验证码
     */
    private void EmptyIdentifyPoint() {
        mTextPwdPoinTextView.setVisibility(View.VISIBLE);
        mTextPwdPoinTextView.setText("请输入验证码");
        mTextPwdPoinTextView.setTextColor(android.graphics.Color.parseColor("#ff361b"));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
